package com.brainsitter;


import java.sql.Date;
import java.sql.Time;
import java.util.ArrayList;
import java.util.Calendar;

import com.brainsitter.db.DBHandler;
import com.brainsitter.db.tables.Profile;
import com.brainsitter.db.tables.Task;
import com.brainsitter.functions.ProgramFunction;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager.LayoutParams;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;

public class TaskTabActivity extends Activity{

	
	Dialog menuDialog;
	
	
	LinearLayout addTaskLinearLayout;
	
	ImageView taskMenuImage;
	ImageView addTaskImageView;
	CheckBox showCompleteTaskCheckBox;
	CheckBox showFailedTaskCheckBox;
	
	DBHandler db;
	
	/*ADD TASK DIALOG*/
	EditText addTaskName;
	EditText addTaskDescription;
	DatePicker addTaskDate;
	TimePicker addTaskTime;
	Button saveAddTaskButton;
	Button cancelAddTaskButton;
	
	/*View Task*/
	ScrollView mainViewLayout;
	LinearLayout innerMainLayout;
	
	

	/** Called when the activity is first created. */
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.task_tab);
        initMenuDialog();
        init();
        
        Profile user = db.getProfile();
        if(user==null){
        	final Dialog userDialog = new Dialog(this);
        	userDialog.setContentView(R.layout.register_user_dialog);
        	final EditText name = (EditText) userDialog.findViewById(R.id.userName);
        	Button addUser = (Button) userDialog.findViewById(R.id.addUser);
			addUser.setOnClickListener(new View.OnClickListener() {
				
				public void onClick(View v) {
					// TODO Auto-generated method stub
					if(!name.getText().toString().isEmpty()){
						Profile user = new Profile();
						user.setName(name.getText().toString());
						user.setPoints(0);
						user.setTwitterName("");
						user.setTwitterPassword("");
						db.addProfile(user);
						userDialog.dismiss();
					}
				}
			});
			userDialog.setTitle("Register User");
			userDialog.show();
        }
        
        
	}
	


	public void onResume(){
		super.onResume();
		innerMainLayout.removeAllViews();
		setDefaultTasks();
	}
	
	
	private void setDefaultTasks(){
		//get all pending only
		ArrayList<Task> tempTasks =  db.getAllTasks();
		ArrayList<Task> tasks = new ArrayList<Task>();
		for(Task t : tempTasks){
			if(isPending(t.getDueDate(),t.getDueTime())){
				tasks.add(t);
			}
		}
		displayTasks(tasks);
		
	}
	
	public void displayTasks(ArrayList<Task> tasks){
		for(int i=0; i<tasks.size(); i++){
			try{
				if(tasks.get(i).getDueDate().compareTo(tasks.get(i-1).getDueDate())!=0){
					//display new header
					makeHeader(ProgramFunction.convertYYYYMMDDToNormal(tasks.get(i).getDueDate()));
				}
			}
			catch(Exception ex){
				makeHeader(ProgramFunction.convertYYYYMMDDToNormal(tasks.get(i).getDueDate()));
			}
			if(!tasks.get(i).getTaskName().isEmpty()){
				makeContent(tasks.get(i).getTaskName()+" - "+tasks.get(i).getTaskDescription()+" on "+ProgramFunction.convertSQLTimeToNormal(tasks.get(i).getDueTime()));
			}
		}
	}
	
	
	public boolean isPending(Date date, Time time){
		Calendar c = Calendar.getInstance();
		if(date.getYear() >= c.get(Calendar.YEAR)-1900){
			Log.d("CHECKING YEAR", "RETURN FALSE");
			return true;
		}
		else{
			if(date.getMonth() >= c.get(Calendar.MONTH)){
				Log.d("CHECKING MONTH", "RETURN FALSE");
				return false;
			}
			else{
				if(date.getDate() >= c.get(Calendar.DATE)){
					Log.d("CHECKING DATE", "RETURN FALSE");
					return true;
				}
				else{
					if(time.getHours() >= c.get(Calendar.HOUR_OF_DAY)){
						Log.d("CHECKING HOUR", "RETURN FALSE");
						return true;
					}
					else{
						if(time.getMinutes() >= c.get(Calendar.MINUTE)){
							Log.d("CHECKING MINUTE", "RETURN FALSE");
							return true;
						}
						else{
							if(time.getSeconds() >= c.get(Calendar.SECOND)){
								Log.d("CHECKING SECOND", "RETURN FALSE");
								return true;
							}
						}
					}
				}
			}
		}
		return false;
	}
	
	
	
	private void makeHeader(String text){
		LinearLayout header = new LinearLayout(this);
		header.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
		header.setBackgroundColor(Color.parseColor("#FFA500"));
		header.setOrientation(LinearLayout.HORIZONTAL);
		header.setGravity(Gravity.CENTER);
		
		TextView headerText = new TextView(this);
		headerText.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
		headerText.setText(text);
		headerText.setGravity(Gravity.CENTER);
		header.addView(headerText);
		innerMainLayout.addView(header);
	}
	
	private void makeContent(String text){
		TextView view = new TextView(this);
		view.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
		view.setText(text);
		innerMainLayout.addView(view);
	}
	
	
	
	private void init(){
		db = new DBHandler(this);
		mainViewLayout = (ScrollView) findViewById(R.id.mainViewLayout);
		innerMainLayout = (LinearLayout) findViewById(R.id.innerMainLayout);
        taskMenuImage = (ImageView) findViewById(R.id.taskMenuImage);
        addTaskImageView = (ImageView) menuDialog.findViewById(R.id.addTaskButton);
        addTaskLinearLayout = (LinearLayout) menuDialog.findViewById(R.id.addTaskLinearLayout);
        showCompleteTaskCheckBox = (CheckBox) menuDialog.findViewById(R.id.showCompleteTaskCheckBox);
        showFailedTaskCheckBox = (CheckBox) menuDialog.findViewById(R.id.showFailedTaskCheckBox);
        taskMenuImage.setOnClickListener(new View.OnClickListener(){

			public void onClick(View v) {
				// TODO Auto-generated method stub
				taskMenuImageOnClick(v);
			}
        	
        });
        
        
        addTaskLinearLayout.setOnClickListener(new View.OnClickListener(){

			public void onClick(View v) {
				// TODO Auto-generated method stub
				addTaskLinearLayoutOnClick(v);
			}
        	
        });
        
        
	}
	
	protected void addTaskLinearLayoutOnClick(View v) {
		// TODO Auto-generated method stub
		final Dialog addTaskDialog = new Dialog(this);

		addTaskDialog.setContentView(R.layout.add_task_dialog);
		addTaskDialog.setTitle("Add Task");
		addTaskDialog.show();
		

		addTaskName = (EditText) addTaskDialog.findViewById(R.id.addTaskName);
		addTaskDescription = (EditText) addTaskDialog.findViewById(R.id.addTaskDescription);
		addTaskDate = (DatePicker) addTaskDialog.findViewById(R.id.addTaskDate);
		addTaskTime = (TimePicker) addTaskDialog.findViewById(R.id.addTaskTime);
		saveAddTaskButton = (Button) addTaskDialog.findViewById(R.id.saveAddTaskButton);
		cancelAddTaskButton = (Button) addTaskDialog.findViewById(R.id.cancelAddTaskButton);

		saveAddTaskButton.setOnClickListener(new View.OnClickListener(){

			public void onClick(View v) {
				// TODO Auto-generated method stub
				//Add Task
				addTaskOnClick(v,addTaskDialog);
				
			}
        	
        });
		
		cancelAddTaskButton.setOnClickListener(new View.OnClickListener(){

			public void onClick(View v) {
				// TODO Auto-generated method stub
				//Cancel
				addTaskDialog.dismiss();
				menuDialog.dismiss();
			}
        	
        });
        
		
		
		
	}

	protected void addTaskOnClick(View v,Dialog d) {
		// TODO Auto-generated method stub
		int numTasks = db.getTaskCount();
		if(numTasks>10){
			Toast.makeText(this, "TOO MANY TASKS ", Toast.LENGTH_SHORT).show();
		}
		else{
			Task task = new Task();
			task.setTaskName(addTaskName.getText().toString());
			task.setTaskDescription(addTaskDescription.getText().toString());
			task.setDueDate(new Date(addTaskDate.getYear()-1900, addTaskDate.getMonth(), addTaskDate.getDayOfMonth()));
			task.setDueTime(new Time(addTaskTime.getCurrentHour(), addTaskTime.getCurrentMinute(), 0));
			db.addTask(task);
			Log.d("Add Task", "Success!");
			d.dismiss();
			menuDialog.dismiss();
			onResume();
		}
	}



	private void initMenuDialog(){
		menuDialog = new Dialog(this);

		menuDialog.setContentView(R.layout.menu_task_form_dialog);
		
		LayoutParams lp = menuDialog.getWindow().getAttributes();    
        //lp.x=150;
        lp.y=90;
        lp.gravity=Gravity.TOP | Gravity.RIGHT;
        lp.dimAmount= 0.5f;            
   //   dialog.getWindow().setAttributes(lp);
	}
	
	

	protected void taskMenuImageOnClick(View v) {
		// TODO Auto-generated method stub
		//Toast.makeText(this, "Add Task", Toast.LENGTH_SHORT).show();
		Profile user = db.getProfile();
		menuDialog.setTitle("Hello "+user.getName());
		menuDialog.show();
	}


	
    
	
}
